#### Replication Code for:
#### Constituency Service and Electoral Accountability in Autocratic Legislatures
#### Author: Erin York
#### Created: 5/30/2024

# this code replicates all data-generated figures and tables in the main text

rm(list = ls())

## Load Packages
library(tidyverse)
library(stargazer)
library(logr)

options("logr.autolog" = TRUE)

# Open the log
lf <- log_open(file.path("logmain.log"))

# Send message to log
log_code()


# load data ---------------------------------------------------------------


# load cross-national dataset
country_panel<- read_csv("df_country_panel.csv")
# load subnational data
# politician level
mpdat<- read_csv("df_mplevel.csv")
# query level
querydat<- read_csv("df_querylevel.csv")
# party-circonscription level
partycirc<- read_csv("df_partylevel.csv")
# party-municipality level
munidat<- read_csv("df_munilevel.csv")


## helper functions ------------------------------------------------------------

# for cluster bootstrapping
block_bs <- function(clust, dat, model){
  nclust <- length(unique(clust))
  levels <- unique(clust)
  samp <- as.vector(sample(levels, size = nclust, replace = T))
  orig <- clust
  dat2 <- plyr::ldply(lapply(samp, FUN = function(x){dat[orig == x,]}), data.frame)
  a <- lm(as.formula(model), data = dat2)
  return(c(coef(a)))
}



# figure 1 ----------------------------------------------------------------

f1<- country_panel %>%
  # filter to include match between legislative and ruler party
  # remove cases with 0 legislative seats and where ruler is non-partisan
  filter(execme == gov1me, execme != "-999", totalseats > 0) %>% 
  # calculate seatshare for ruling party and remaining seatshare
  mutate(seatsharegov = gov1seat/totalseats,
         seatsharenongov = 1-seatsharegov) %>%
  group_by(year) %>%
  # identify average and percentiles
  summarise(mu = mean(seatsharegov), cilo = quantile(seatsharegov, .05), cihi = quantile(seatsharegov, .95),
            n = n()) %>%
  ggplot(aes(x = year, y = mu)) + 
  geom_pointrange(aes(ymin = cilo, ymax = cihi), color = "gray", size = .3) + geom_point() +
  theme_bw() + ylim(c(0, 1)) + xlab("") + ylab("Prop. seats held by ruling party")
f1

ggsave(f1, filename = "Figure1.pdf",
      width = 8, height = 5)


# figure 2 ----------------------------------------------------------------

# nation casework and complaint should be defined earlier
f2<- querydat %>%
  # province - includes both provinces and prefectures (urban equivalent)
  mutate(Province = ifelse(provdum + prefdum > 0, 1, 0)) %>%
  rename(Nation =natdum,
         Region = regdum,
         Commune = commdum,
         Georeference = anyplace,
         Casework = casework,
         Complaint = complaint) %>%
  dplyr::select(Nation, Region, Province, Commune, Georeference, Casework, Complaint) %>%
  # generate summary statistics across query content
  summarise_each(funs(mean)) %>%
  gather(attribute, mn) %>%
  mutate(type = "Written (n = 27196)") %>%
  mutate(attribute = fct_reorder(attribute, mn),
         rounded = round(mn, digits = 2)) %>%
  # generate bar plot
  ggplot(aes(x = attribute, y = mn, fill = type)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = rounded, hjust = -.5), 
            position = position_dodge(width = 1)) +
  ylim(c(0, 1)) +
  theme_bw() +
  coord_flip() +
  ylab("Proportion of queries with specified content reference") +
  xlab("") +
  guides(fill = "none") +
  scale_fill_manual(values = c("#1F78B4"))
f2

ggsave(f2, file = "Figure2.pdf",
      width = 8, height = 5)


# table 1 -----------------------------------------------------------------


set.seed(123456)

writ1 <- lm(log_nwrit ~ royalist, data = mpdat)
bs <- replicate(block_bs(mpdat$party_full, mpdat, writ1), n = 2000)
se1 <- apply(bs, MARGIN = 1, FUN = sd, na.rm = T)

writ2 <- lm(log_nwrit ~ royalist + leader + natlist +
              former + actif, data = mpdat)
bs <- replicate(block_bs(mpdat$party_full, mpdat, writ2), n = 2000)
se2 <- apply(bs, MARGIN = 1, FUN = sd, na.rm = T)

writ3 <- (lm(log_nwrit ~ royalist + gov_full + leader + female + youth  +
               former + actif, data = mpdat))
bs <- replicate(block_bs(mpdat$party_full, mpdat, writ3), n = 2000)
se3 <- apply(bs, MARGIN = 1, FUN = sd, na.rm = T)


sink("Table1.tex")
stargazer(writ1, writ2, writ3,
          se = list(se1,  se2,  se3),
          dep.var.labels = "Log Written Questions",
          star.cutoffs = c(0.05, 0.01, 0.001),
          omit = c("Constant"),
          omit.stat = c("f", "ser", "adj.rsq"),
          covariate.labels = c("Royalist", "Governing Coalition", "Committee Leader",
                               "National List", "Female", "Youth",
                               "2007 Parliament", "Civic Engagement"))
sink()

## table 2 ---------------------------------------------------------------------


win3 <- (lm(delta_voteshare ~ n_wr_ln + n_or_ln + npols + region + log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban, data = partycirc))

win4 <- (lm(delta_voteshare ~ n_wr_ln + n_or_ln + npols + factor(circid), data = partycirc))

win5 <- (lm(delta_votes ~ n_wr_ln + n_or_ln + npols  +  region + log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban, data = partycirc))

win6 <- (lm(delta_votes ~ n_wr_ln + n_or_ln + npols  + factor(circid), data = partycirc))

sink(file = "Table2.tex")
stargazer(win3, win4, win5, win6,
          dep.var.labels = c("Change in Voteshare 2011-2016", "Change in Votes 2011-2016"),
          star.cutoffs = c(0.05, 0.01, 0.001),
          
          omit = c("Constant", "reg", "circ*",
                   "internet", "unem", "ama", "illit", "population", "urb"),
          covariate.labels = c("Log Written", "Log Oral",
                               "No. District Seats"),
          add.lines = list(c("Mean DV",  "0.00", "0.00", "2338", "2338"),
                           c("Region FEs", "\\checkmark", "", "\\checkmark", ""),
                           c("District Controls", "\\checkmark", "", "\\checkmark", ""),
                           c("District FEs", "",  "\\checkmark", "", "\\checkmark")),
          omit.stat = c("adj.rsq","f", "ser"))
sink()


## table 3 ---------------------------------------------------------------------

roy1 <- (lm(delta_voteshare ~ n_wr_ln + 
              region + log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban , 
            data = filter(partycirc, royalist == 1)))

roy2 <- (lm(delta_voteshare ~ n_wr_ln +
              region +  log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban , 
            data = filter(partycirc, royalist == 0)))

roy3 <- (lm(delta_voteshare ~ n_wr_ln * royalist + 
              region +  log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban, 
            data = partycirc))

roy4 <- (lm(delta_votes ~ n_wr_ln + 
              region +  log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban, 
            data = filter(partycirc, royalist == 1)))

roy5 <- (lm(delta_votes ~ n_wr_ln +
              region +  log(population) +
              internet + unemployment + illiteracy + amazigh_low + urban, 
            data = filter(partycirc, royalist == 0)))

roy6 <- (lm(delta_votes ~ n_wr_ln * royalist   +
              region +  log(population) +
              internet + unemployment + illiteracy +amazigh_low + urban, 
            data = partycirc))

sink("Table3.tex")
stargazer(roy1, roy2, roy3, roy4, roy5, roy6,
          covariate.labels = c("Log Written", "Royalist", "Log Writ*Royalist"),
          omit = c("Constant", "reg", "circ*", "internet", "unem", "ama", "illit", "pop*", "urb"),
          star.cutoffs = c(0.05, 0.01, 0.001),
          dep.var.labels = c("Change in Voteshare 2011-2016", "Change in Votes 2011-2016"),
          no.space = T,
          omit.stat = c("adj.rsq", "f", "ser"),
          add.lines = list(c("Sample", "Royalist", "Opposition", "All", "Royalist", "Opposition", "All"),
                           c("Region FEs", rep("\\checkmark", 6)),
                           c("Dem. Controls", rep("\\checkmark", 6))))
sink()

## table 4 ---------------------------------------------------------------------

reg4a <- lm(voteshare2015 ~ logrefpre + logpop + nparties + party_circ + seatprop09,
            munidat)

reg4b <- lm(voteshare2015 ~ logrefpre + logpop + nparties + seatprop09 + party_circ,  
            filter(munidat, provname == 0))

reg4c <- lm(voteshare2015 ~ loglocalpre + logpop + nparties + party_circ + seatprop09, 
            munidat)

reg4d <- lm(voteshare2015 ~ loglocalpre + party_circ + logpop + nparties + seatprop09, 
            filter(munidat, provname == 0))


sink("Table4.tex")
stargazer(reg4a, reg4b, reg4c, reg4d,
          covariate.labels = c("Log References (Any)", "Log References (Local)",
                               "Log Pop", "No. Parties", "2009 Seatshare"),
          star.cutoffs = c(0.05, 0.01, 0.001),
          omit = c("Constant", "party_circ"),
          omit.stat = c("f", "ser", "adj.rsq"),
          add.lines = list(c("Party-District FE", rep("\\checkmark", 4)),
                           c("Unique Toponym Subset", "", "\\checkmark", "", "\\checkmark")),
          dep.var.labels = "2015 Municipal Voteshare")
sink()


####

log_close()

